package com.example.mykotlin.base.interceptor

import cn.dev33.satoken.stp.StpUtil
import com.example.mykotlin.base.auth.PoiuyCipher
import com.example.mykotlin.base.result.ServiceException
import com.example.mykotlin.base.util.GetBean
import com.example.mykotlin.base.util.tryReturn
import com.example.mykotlin.controller.AuthController
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
import org.springframework.stereotype.Component
import org.springframework.web.servlet.HandlerInterceptor

@Component
class DeviceInterceptor : HandlerInterceptor {
    companion object {
        const val TOKEN_NAME = "token"
    }

    @Throws(Exception::class)
    override fun preHandle(request: HttpServletRequest, response: HttpServletResponse, handler: Any): Boolean {
        val device = tryReturn {
            StpUtil.getLoginDevice()
        }
        val loginId = tryReturn {
            StpUtil.getLoginId().toString()
        }
        if (device != null && loginId != null) {
            val deviceInfo = GetBean.redisTemplate().opsForValue()["${AuthController.DEVICE}:${device}:${loginId}"]
            val deviceHeader = PoiuyCipher.rsaDecryptDevice(
                request.getHeader(TOKEN_NAME) ?: throw ServiceException("未获取到相关信息", "401")
            )
            if (deviceInfo != null && deviceHeader != deviceInfo) throw ServiceException(
                "该设备无法使用该登录信息", "403"
            )
        }
        return true
    }

}